package com.bdqn.t330.config;

import com.bdqn.t330.service.UserService;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .formLogin()
                .loginPage("/login").permitAll() //配置登录页面并对该页面进行授权配置
                .loginProcessingUrl("/dologin")//登录controller请求
                .usernameParameter("username") //指定登录界面用户名文本框的name值，如果没有指定，默认属性名必须为username
                .passwordParameter("password")//指定登录界面密码密码框的name值，如果没有指定，默认属性名必须为password
                .successForwardUrl("/dologin")  //认证成功 forward 跳转路径,始终在认证成功之后跳转到指定请求
                .and()
                .authorizeRequests()
                .antMatchers("/images/**","/js/**","/css/**","/fonts/**","/localcss/**","/localjs/**").permitAll()  //放行静态资源
                //.antMatchers("/admin").hasRole("admin")  //针对admin角色能访问/admin
                //.antMatchers("/dept").hasAuthority("ROLE_dept")    //针对dept角色能访问/dept
//                .antMatchers("/chance/list").hasAuthority("L0101")
//                .antMatchers("/plan/list").hasAuthority("L0102")
                .anyRequest().access("@myRBACService.hasPermission(request,authentication)")
                .anyRequest().authenticated()//任何请求都需要经过验证
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      //  auth.inMemoryAuthentication()
                //.passwordEncoder(NoOpPasswordEncoder.getInstance())
      //          .passwordEncoder(new BCryptPasswordEncoder())
      //          .withUser("admin").password("$2a$10$nVGoX3KHyltKclPNNkOV6e8dOLGZxesKuwKW3ZEuUD.0/7Wm01jN.").roles("admin")
      //          .and()
      //          .withUser("dept").password("$2a$10$nVGoX3KHyltKclPNNkOV6e8dOLGZxesKuwKW3ZEuUD.0/7Wm01jN.").roles("dept");
        //基于数据库认证授权
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }
}
